import os
from flask import Response


def build_file_response(item_path):
    def file_iterator(file_path_iterator, chunk_size=512):
        """
        防止文件过大，导致内存溢出
        """
        with open(file_path_iterator, mode='rb') as f:
            while True:
                chunk_file = f.read(chunk_size)
                if chunk_file:
                    yield chunk_file
                else:
                    break

    return Response(
        file_iterator(item_path),
        mimetype='application/octet-stream',
        headers={
            'Content-Disposition': f"attachment;filename={os.path.basename(item_path)}"
        }
    )
